package org.jeecg.modules.wechat.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.constant.RedisConstant;
import org.jeecg.constant.WXConstant;
import org.jeecg.modules.wechat.service.WxService;
import org.jeecg.modules.wechat.util.WeChatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * TODO: 微信相关业务接口实现类
 *
 * @author Zhang Hao yu
 * @date 2020/11/11 8:47
 */
@Service
public class WxServiceImpl implements WxService {
    @Autowired
    private RedisUtil redisUtil;


    @Override
    public String getAccessToken(){
        Object o = redisUtil.get(RedisConstant.WX_ACCESS_TOKEN);
        if (o!=null){
            // redis中没有过期
            return (String)o;
        }
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid="+ WXConstant.WX_APPID +
                "&secret="+WXConstant.WX_SECRET;
        String str = WeChatUtil.httpRequest(url, "GET", null);
        JSONObject jsonObject = JSON.parseObject(str);
        // 获取token和过期时间，存入redis中，供其他业务使用
        String accessToken = jsonObject.getString("access_token");
        Integer expiresIn = jsonObject.getInteger("expires_in");
        redisUtil.set(RedisConstant.WX_ACCESS_TOKEN,accessToken,expiresIn);
        return accessToken;
    }
}